<?php

/* * ************************************************************************************************
  |
  | AudioShare - Audio Sharing Script
  | http://www.audiosharescript.com
  | webmaster@audiosharescript.com
  |
  |**************************************************************************************************
  |
  | By using this software you agree that you have read and acknowledged our End-User License
  | Agreement available at http://www.audiosharescript.com/eula.html and to be bound by it.
  |
  | Copyright (c) 2010 AudioShareScript.com. All rights reserved.
  |************************************************************************************************* */

include("include/config.php");
include("include/functions/import.php");
$thebaseurl = $config['baseurl'];

$category="";
if(isset($_REQUEST["cat"]) && $_REQUEST["cat"]!="")
    $category=intval($_REQUEST["cat"]);

$PlaylistMsg = "";
if (isset($_POST["new_playlist"]) && $_POST["new_playlist"] == "1") {
    if (isset($_POST["playlist_title"])) {
        $playlist_title = mysql_real_escape_string(trim($_POST["playlist_title"]));
        if ($playlist_title != "") {

            $playlist_title = trim(mysql_real_escape_string($playlist_title));
            ## check if playlist with this name already exists...
            $query = "select count(*) as count from playlists where playlist_title='" . $playlist_title . "' and active='1'";
            $executequery = $conn->Execute($query);
            $Isexist = $executequery->fields["count"];

            if ($Isexist != 0) {
                $errorPlaylist = "Playlist not created as playlist with this title already exixts.";
            } else {
                $query = "INSERT INTO playlists SET playlist_title='" . $playlist_title . "',USERID='" . mysql_real_escape_string($_SESSION[USERID]) . "', date_added='" . date("Y-m-d") . "'";
                $conn->execute($query);
                $playlist_added = 1;
            }
        } else {
            $errorPlaylist = "Playlist title cannot be empty.";
        }
    }
}
STemplate::assign('errorPlaylist', $errorPlaylist);
//$AudiosAdded=0;
if (isset($_POST["addtoplaylist"])) {
    $resultArray = array();
    $playlistsUpdated = array();
    if (!empty($_POST["audios"]) && !empty($_POST["playlist"])) {

        ## Add audios to the playlists...
        if (!empty($resultArray))

        ## add audios only if they are not already added to that playlist...
            echo implode(",", $_POST["playlist"]);
        $PlaylistAudioList = array();
        ## get the audios of the selected playlists...
        $query = "select distinct PLAYLISTID,AUDIOID from playlist_audios where PLAYLISTID in (" . implode(",", $_POST["playlist"]) . ")";
        $results = $conn->execute($query);
        $Audios = $results->getrows();
        foreach ($Audios as $key => $val) {
            if (!is_array($PlaylistAudioList[$val["PLAYLISTID"]]))
                $PlaylistAudioList[$val["PLAYLISTID"]] = array();
            if (!in_array($val["AUDIOID"], $PlaylistAudioList[$val["PLAYLISTID"]]))
                $PlaylistAudioList[$val["PLAYLISTID"]][] = $val["AUDIOID"];
        }

        ## check which playlists are updated so that neeed to update only those playlists and update their xml files...
        foreach ($_POST["playlist"] as $val) {
            $diff = array();
            ## calculate the audio difference for the playlist...
            if (is_array($PlaylistAudioList[$val])) {
                $diff = array_diff($_POST["audios"], $PlaylistAudioList[$val]);
                ## if there is difference than only we need to update that playlist...
                if (!empty($diff)) {
                    $resultArray[$val] = $diff;
                    $playlistsUpdated[] = $val;
                }
            } else {
                $resultArray[$val] = $_POST["audios"];
                $playlistsUpdated[] = $val;
            }
        }

        if (AddAudiosToPlaylist($resultArray)) {
            $PlaylistMsg = "Audios added to the playlists successfully.";
        } else {
            $PlaylistMsg = "Audios are already to the selected playlists.";
        }
        ## create xml files for the playlist...
        if (!empty($playlistsUpdated))
            create_playlist_xml($playlistsUpdated);
    } else {
        if (empty($_POST["audios"])) {
            $PlaylistMsg = "Please select atleast one audio to add to playlist.";
        } else if (empty($_POST["playlist"])) {
            $PlaylistMsg = "Please select atleast one playlist to add audios to.";
        }
    }
}

//Get Variables
$getsearchfor = "audios";
$searchfor = "audios";
$getsortby = htmlentities(strip_tags($_REQUEST[sortby]));
$sortby = escape($getsortby);
$getpage = htmlentities(strip_tags($_REQUEST[page]));
$page = escape($getpage);
$search_data = escape($_REQUEST[searchterm]);

$searchCountry = "";
$searchYear = "";
$searchArtist = "";
$searchTitle = "";

$dataArray = split("_", $search_data);
$searchterm = escape($dataArray[0]);

$searchCountry = escape($dataArray[1]);
$searchYear = escape($dataArray[2]);
$searchArtist = escape($dataArray[3]);
$searchTitle = escape($dataArray[4]);

if ($sortby == "a") {
    $sort = "asc";
} else {
    $sortby = "z";
    $sort = "desc";
}

if ($page == "") {
    $page = "1";
}
$currentpage = $page;

if ($page >= 2) {
    $pagingstart = ($page - 1) * $config[items_per_page];
} else {
    $pagingstart = "0";
}



if ($getsearchfor == "audios") {
    STemplate::assign('getsearchfor', $getsearchfor);
    $cond = "";
    $join = "";
    if ($searchCountry != "0" && $searchCountry != "") {
        /* if ($join == "")
          $join = "left join members m on (a.USERID=m.USERID)"; */
        $cond .=" and a.country='$searchCountry'";
    }

    if ($searchYear != "0" && $searchYear != "") {
        $cond .=" and YEAR(a.date_added)='$searchYear'";
    }

    if ($searchArtist != "") {
        $cond .=" and a.artist like '%$searchArtist%'";
    }

    if ($searchTitle != "0" && $searchTitle != "") {
        $cond .=" and a.AUDIOID='$searchTitle'";
    }
    
    if($category!=""){
        $cond .=" and a.categories='$category'";
    }
    
    if ($getsearchfor == "audios") {
        $queryselected = "SELECT count(*) as total from audios a $join WHERE a.public='1' AND a.active='1' AND (a.title like '%" . mysql_real_escape_string($searchterm) . "%' OR a.description like '%" . mysql_real_escape_string($searchterm) . "%' OR tags like '%" . mysql_real_escape_string($searchterm) . "%') $cond order by a.rating $sort limit $config[maximum_results]";
        $query2 = "SELECT a.* from audios a $join WHERE a.public='1' AND a.active='1' AND (a.title like '%" . mysql_real_escape_string($searchterm) . "%' OR a.description like '%" . mysql_real_escape_string($searchterm) . "%' OR a.tags like '%" . mysql_real_escape_string($searchterm) . "%') $cond order by a.rating $sort limit $pagingstart, $config[items_per_page]";
        $showtitle = "$lang[798]";
        $mainmenu = "7";
    }
}

STemplate::assign('showtitle', $showtitle);

if ($searchterm != "") {
    STemplate::assign('pagetitle', $searchterm . " $lang[664] - " . $showtitle);
} else {
    STemplate::assign('pagetitle', $showtitle);
}

STemplate::assign('mainmenu', $mainmenu);

$executequeryselected = $conn->Execute($queryselected);

$totalvideos = $executequeryselected->fields['total'];
if ($totalvideos > 0) {

    if ($executequeryselected->fields['total'] <= $config[maximum_results]) {
        $total = $executequeryselected->fields['total'];
    } else {
        $total = $config[maximum_results];
    }

    $toppage = ceil($total / $config[items_per_page]);
    if ($toppage == 0) {
        $xpage = $toppage + 1;
    } else {
        $xpage = $toppage;
    }


    $executequery2 = $conn->Execute($query2);
    $users = $executequery2->getrows();
    $beginning = $pagingstart + 1;
    $ending = $pagingstart + $executequery2->recordcount();

    $pagelinks = "";
    $k = 1;
    $theprevpage = $currentpage - 1;
    $thenextpage = $currentpage + 1;

    if ($currentpage > 0) {
        ## new way of paging starts here...
        $pagelinks.='<table width="100%" cellspacing="2" cellpadding="2" border="0">';
        $pagelinks.='<tr>';
        $pagelinks.='<td width="33%">';
        $pagelinks.='<a href="javascript:void(0);"><img height="16" width="16" border="0" align="absmiddle" src="' . $config[imageurl] . '/ico_rss_s.gif" alt="RSS"  /></a>';
        $pagelinks.='<span class="pag"> page ' . $currentpage . ' of ' . $total . '</span>';
        $pagelinks.='</td>';
        $pagelinks.='<td width="33%" align="right">';
        $pagelinks.="<div class=\"pagination\">";
        if ($currentpage > 1) {
            $pagelinks.="<a href='$thebaseurl/search/audios/$sortby/1/$search_data'>$lang[611]</a>";
            $pagelinks.="<span class='ellipsis'>...</span>";
            $pagelinks.="<a href='$thebaseurl/search/audios/$sortby/$theprevpage/$search_data'>&laquo; $lang[612]</a>";
        } else {
            $pagelinks.="<span>&lt;</span>";
        }
        $counter = 0;
        $lowercount = $currentpage - 5;
        if ($lowercount <= 0)
            $lowercount = 1;

        while ($lowercount < $currentpage) {
            $pagelinks.="<a href='$thebaseurl/search/audios/$sortby/$lowercount/$search_data'>$lowercount</a>";
            $lowercount++;
            $counter++;
        }

        $pagelinks.="<span class='current'><span>$currentpage</span></span>";

        $uppercounter = $currentpage + 1;

        while (($uppercounter < $currentpage + 10 - $counter) && ($uppercounter <= $toppage)) {
            $pagelinks.="<a href='$thebaseurl/search/audios/$sortby/$uppercounter/$search_data'>$uppercounter</a>";
            $uppercounter++;
        }

        if ($currentpage < $toppage) {
            $pagelinks.="<a href='$thebaseurl/search/audios/$sortby/$thenextpage/$search_data'>$lang[613] &raquo;</a>";
            $pagelinks.="<span class='ellipsis'>...</span>";
            $pagelinks.="<a href='$thebaseurl/search/audios/$sortby/$toppage/$search_data'>$lang[614]</a>";
        } else {
            $pagelinks.="<span class=\"disable\">&gt;</span>";
        }
        $pagelinks.="</div>";
        $pagelinks.='</td>';
        $pagelinks.='</tr>';
        $pagelinks.="</table>";
        ## new way of paging ends here...
    }
} else {
    $error = $lang['665'] . " " . $searchterm;
    STemplate::assign('error', $error);
}

## get the list of the playlists to add to the playlists...
$userPlaylists = array();
$formAction = "";
if ($_SESSION[USERID] != "" && $_SESSION[USERID] >= 0 && is_numeric($_SESSION[USERID])) {
    $playlistData = array();
    $playlistData = getPlaylists($_SESSION[USERID]);
    if (!empty($playlistData)) {
        foreach ($playlistData as $key => $val) {
            $userPlaylists[] = array("id" => $val["PLAYLISTID"], "title" => $val["playlist_title"]);
        }
    }
    $formAction = $config[baseurl] . "/search/audios/$sortby/$currentpage/$search_data";
}
## list of the playlists retrived if user is logged in...
//TEMPLATES BEGIN
STemplate::assign('beginning', $beginning);
STemplate::assign('ending', $ending);
STemplate::assign('pagelinks', $pagelinks);
STemplate::assign('total', $total);
STemplate::assign('listaudios', $users);
STemplate::assign('userPlaylists', $userPlaylists);
STemplate::assign('userID', $_SESSION[USERID]);
STemplate::assign('formAction', $formAction);
STemplate::assign('PlaylistMsg', $PlaylistMsg);
STemplate::display('header.tpl');
STemplate::display('search.tpl');
STemplate::display('footer.tpl');
//TEMPLATES END
?>	